package com.hdcircles.autoform.ui.label.adapter;


import android.app.DatePickerDialog;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.cengalabs.flatui.views.FlatCheckBox;
import com.cengalabs.flatui.views.FlatEditText;
import com.cengalabs.flatui.views.FlatRadioButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hdcircles.autoform.R;
import com.hdcircles.autoform.app.Constants;
import com.hdcircles.autoform.model.bean.ChooseQuestionBean;
import com.hdcircles.autoform.model.bean.QuestionBean;
import com.hdcircles.autoform.model.http.LocationHelper;
import com.hdcircles.autoform.util.SystemUtil;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.jaeger.ninegridimageview.NineGridImageViewAdapter;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.finalteam.rxgalleryfinal.RxGalleryFinal;
import cn.finalteam.rxgalleryfinal.bean.MediaBean;
import cn.finalteam.rxgalleryfinal.imageloader.ImageLoaderType;
import cn.finalteam.rxgalleryfinal.rxbus.RxBusResultSubscriber;
import cn.finalteam.rxgalleryfinal.rxbus.event.ImageMultipleResultEvent;

/**
 *
 * Created by hdcircles on 2016/10/15.
 */

public class QuestionAdapter extends RecyclerView.Adapter<QuestionAdapter.ViewHolder> {

    private List<QuestionBean> questionBeenList;

    private LocationListener locationListener;

    private addChooseListener chooseListener;

    private onImageListener imageListener;

    private LocationHelper locationHelper;

    private getMapListener mapListener;

    private jumpToImageViewListener toImageViewListener;


    @Inject
    public QuestionAdapter(LocationHelper locationHelper) {
        this.locationHelper = locationHelper;
    }


    public void setQuestionBeenList(List<QuestionBean> questionBeenList) {
        this.questionBeenList = questionBeenList;
    }

    @Override
    public QuestionAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        switch (viewType) {
            case Constants.TYPE_SINGLE_CHOOSE:
                return new RadioViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_radio, parent, false));
            case Constants.TYPE_MULTIPLE_CHOOSE:
                return new CheckBoxViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_checkbox, parent, false));
            case Constants.TYPE_TEXT:
                return new TextViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_text, parent, false));
            case Constants.TYPE_PICTURE:
                return new PictureViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_picture, parent, false));
            case Constants.TYPE_LOCATION:
                return new LocationViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_location, parent, false));
            case Constants.TYPE_TIME:
                return new TimeViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_question_time, parent, false));
        }
        return null;
    }

    @Override
    public int getItemViewType(int position) {
        return questionBeenList.get(position).getType();
    }

    @Override
    public void onBindViewHolder(final QuestionAdapter.ViewHolder holder, int position) {
        final QuestionBean question = questionBeenList.get(position);
        holder.tvNumber.setText(holder.context.getResources().getString(R.string.qt_number, String.valueOf(position + 1)));
        holder.tvTitle.setText(question.getQuestionTitle());
        if (question.isRequired()) {
            holder.ivRequired.setVisibility(View.VISIBLE);
        } else {
            holder.ivRequired.setVisibility(View.GONE);
        }
        if (holder instanceof RadioViewHolder) {
            ((RadioViewHolder) holder).rgChoice.removeAllViews();
            RadioGroup.LayoutParams radioLp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT);
            radioLp.bottomMargin = SystemUtil.dp2px(holder.context, 8);
            if (0 == question.getChooseQuestion().size()) {
                chooseListener.getChooseQuestion(question);
            } else {
                ((RadioViewHolder) holder).progressBar.setVisibility(View.GONE);
            }
            final List<ChooseQuestionBean> chooseList = question.getChooseQuestion();
            final List<FlatRadioButton> radioButtonList = new ArrayList<>();
            for (final ChooseQuestionBean choiceBean : chooseList) {
                FlatRadioButton button = (FlatRadioButton) View.inflate(holder.context, R.layout.view_radio, null);
                radioButtonList.add(button);
                button.setTextSize(18);
                button.setText(choiceBean.getInfo());
                button.setEnabled(true);
                button.setChecked(choiceBean.getIsSelect());
                button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        for (FlatRadioButton radioButton : radioButtonList) {
                            radioButton.setChecked(false);
                        }
                        choiceBean.setIsSelect(b);
                        question.setCompleted(true);
                        compoundButton.setChecked(b);
                    }
                });
                ((RadioViewHolder) holder).rgChoice.addView(button, radioLp);
            }
        } else if (holder instanceof CheckBoxViewHolder) {
            ((CheckBoxViewHolder) holder).llCheckBox.removeAllViews();
            LinearLayout.LayoutParams llLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            llLayoutParams.bottomMargin = SystemUtil.dp2px(holder.context, 8);
            if (0 == question.getChooseQuestion().size()) {
                chooseListener.getChooseQuestion(question);
            } else {
                ((CheckBoxViewHolder) holder).progressBar.setVisibility(View.GONE);
            }
            for (final ChooseQuestionBean choice : question.getChooseQuestion()) {
                FlatCheckBox checkBox = (FlatCheckBox) View.inflate(holder.context, R.layout.view_check_box, null);
                checkBox.setTextSize(18);
                checkBox.setText(choice.getInfo());
                checkBox.setEnabled(true);
                checkBox.setChecked(choice.getIsSelect());
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        choice.setIsSelect(b);
                        question.setCompleted(true);
                    }
                });
                ((CheckBoxViewHolder) holder).llCheckBox.addView(checkBox, llLayoutParams);
            }

        } else if (holder instanceof TextViewHolder) {
            final FlatEditText etText = ((TextViewHolder) holder).etText;
            etText.setText(question.getTextAnswer());
            etText.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    QuestionBean updatedQuestion = questionBeenList.get(holder.getAdapterPosition());
                    updatedQuestion.setTextAnswer(etText.getText().toString().trim());
                    if (0 != etText.getText().length())
                        updatedQuestion.setCompleted(true);
                }
            });


        } else if (holder instanceof LocationViewHolder) {
            final FlatEditText etLocation = ((LocationViewHolder) holder).etLocation;
            etLocation.setText(question.getLocation());
            etLocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    QuestionBean updatedQuestion = questionBeenList.get(holder.getAdapterPosition());
                    mapListener.getMap(updatedQuestion);
                }
            });

            ((LocationViewHolder) holder).ivLocation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ((LocationViewHolder) holder).ivLocation.setVisibility(View.GONE);
                    ((LocationViewHolder) holder).progressBar.setVisibility(View.VISIBLE);
                    locationListener.getLocation(((LocationViewHolder) holder).itemView);
                }
            });
            final LocationAdapter locationAdapter = new LocationAdapter();
            ((LocationViewHolder) holder).rvLocation.setLayoutManager(new LinearLayoutManager(((LocationViewHolder) holder).itemView.getContext()));
            ((LocationViewHolder) holder).rvLocation.setAdapter(locationAdapter);
            locationAdapter.setItemClickListener(new LocationAdapter.onItemClickListener() {
                @Override
                public void onItemClick(HashMap<String, String> map) {
                    etLocation.setText(map.get("name"));
                    question.setLocation(map.get("name"));
                    locationAdapter.setLocationList(null);
                }
            });
            etLocation.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    QuestionBean updatedQuestion = questionBeenList.get(holder.getAdapterPosition());
                    String string = ((LocationViewHolder) holder).etLocation.getText().toString().trim();
                    List<HashMap<String, String>> locationList = locationHelper.searchLocation(string);
                    locationAdapter.setLocationList(locationList);
                    updatedQuestion.setLocation(string);
                    if (0 != etLocation.getText().length()) updatedQuestion.setCompleted(true);
                }
            });

        } else if (holder instanceof TimeViewHolder) {
            final FlatEditText etTime = ((TimeViewHolder) holder).etTime;
            etTime.setText("");
            etTime.setText(question.getDate());
            etTime.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Calendar c = Calendar.getInstance();
                    new DatePickerDialog(holder.context, R.style.AppTheme_Dark_Dialog, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
                            int m = i1 + 1;
                            String year = String.valueOf(i);
                            String month = m > 9 ? String.valueOf(m) : "0" + m;
                            String day = i2 > 9 ? String.valueOf(i2) : "0" + i2;
                            String date = year + "/" + month + "/" + day;
                            QuestionBean updatedQuestion = questionBeenList.get(holder.getAdapterPosition());
                            updatedQuestion.setDate(date);
                            updatedQuestion.setCompleted(true);
                            etTime.setText(date);
                        }
                    }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)).show();
                }
            });
        } else if (holder instanceof PictureViewHolder) {
            if (null != question.getPicture() && 0 != question.getPicture().length()) {
                try {
                    List<String> pictureList = new Gson().fromJson(question.getPicture(), new TypeToken<List<String>>() {
                    }.getType());
                    question.setPictureList(pictureList);
                    ((PictureViewHolder) holder).ivPicture.setVisibility(View.INVISIBLE);
                    ((PictureViewHolder) holder).bind(question);
                }catch (Exception e){
                        Glide.with(((PictureViewHolder) holder).itemView.getContext())
                        .load(question.getPicture())
                        .into(((PictureViewHolder) holder).ivPicture);
                }
                ((PictureViewHolder) holder).ivChange.setVisibility(View.VISIBLE);
            }
            ((PictureViewHolder) holder).ivPicture.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    QuestionBean updateQuestion = questionBeenList.get(holder.getAdapterPosition());
                    if (null != updateQuestion.getPicture() && 0 != updateQuestion.getPicture().length()) {
                        toImageViewListener.onImage(updateQuestion.getPicture(), ((PictureViewHolder) holder).ivPicture);
                        return;
                    }
                    pickImage(view.getContext(), updateQuestion);
                }
            });
            ((PictureViewHolder) holder).ivChange.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    QuestionBean updateQuestion = questionBeenList.get(holder.getAdapterPosition());
                    pickImage(view.getContext(), updateQuestion);
                }
            });

            ((PictureViewHolder) holder).setOnItemImageListener(new PictureViewHolder.onItemImageListener() {
                @Override
                public void onClick(int index, List<String> list, ImageView imageView) {
                    toImageViewListener.onImage(list.get(index), imageView);
                }
            });
        }
    }

    private void pickImage(Context context, final QuestionBean updateQuestion) {
        RxGalleryFinal
                .with(context)
                .image()
                .multiple()
                .maxSize(4)
                .imageLoader(ImageLoaderType.GLIDE)
//                .subscribe(new RxBusResultSubscriber<ImageRadioResultEvent>() {
//
//                    @Override
//                    protected void onEvent(ImageRadioResultEvent imageRadioResultEvent) throws Exception {
//                        String path = imageRadioResultEvent.getResult().getOriginalPath();
//                        Bitmap bitmap = BitmapFactory.decodeFile(path);
//                        ((PictureViewHolder) holder).ivPicture.setImageBitmap(bitmap);
//                        QuestionBean questionBean = questionBeenList.get(holder.getAdapterPosition());
//                        imageListener.upLoadImage(path, questionBean);
//                    }
//                })
                .subscribe(new RxBusResultSubscriber<ImageMultipleResultEvent>() {

                    @Override
                    protected void onEvent(ImageMultipleResultEvent imageMultipleResultEvent) throws Exception {
                        List<String> picList = new ArrayList<>();
                        updateQuestion.setPictureList(picList);
                        List<MediaBean> imageList = imageMultipleResultEvent.getResult();
                        imageListener.startUpLoad();
                        for (int i = 0; i < imageList.size(); i++) {
                            String path = imageList.get(i).getOriginalPath();
//                            picList.add(path);
//                            Bitmap bitmap = BitmapFactory.decodeFile(path);
//                            ((PictureViewHolder) holder).ivPicture.setImageBitmap(bitmap);
                            if (i == imageList.size() - 1) {
                                imageListener.lastImage(path, updateQuestion);
                            } else {
                                imageListener.upLoadImage(path, updateQuestion);
                            }
                        }
                    }
                })
                .openGallery();
    }

    @Override
    public void onViewAttachedToWindow(ViewHolder holder) {
        super.onViewAttachedToWindow(holder);
    }

    @Override
    public void onViewDetachedFromWindow(ViewHolder holder) {
        super.onViewDetachedFromWindow(holder);
//        if (holder instanceof LocationViewHolder){
//            ((LocationViewHolder) holder).mapView.onPause();
//        }
    }

    @Override
    public void onViewRecycled(ViewHolder holder) {
        super.onViewRecycled(holder);
//        if (holder instanceof LocationViewHolder){
//            ((LocationViewHolder) holder).mapView.onDestroy();
//        }
    }

    public void setImageListener(onImageListener imageListener) {
        this.imageListener = imageListener;
    }

    public interface onImageListener {

        void startUpLoad();

        void upLoadImage(String path, QuestionBean questionBean);

        void lastImage(String path, QuestionBean questionBean);
    }

    public void setToImageViewListener(jumpToImageViewListener toImageViewListener) {
        this.toImageViewListener = toImageViewListener;
    }

    public interface jumpToImageViewListener {
        void onImage(String url, View view);
    }

    public List<QuestionBean> getQuestionBeenList() {
        return questionBeenList;
    }

    public void setLocationListener(LocationListener locationListener) {
        this.locationListener = locationListener;
    }

    public void setChooseListener(addChooseListener chooseListener) {
        this.chooseListener = chooseListener;
    }

    public interface LocationListener {
        void getLocation(View itemView);

    }


    public void setMapListener(getMapListener mapListener) {
        this.mapListener = mapListener;
    }

    public interface getMapListener {
        void getMap(QuestionBean questionBean);
    }

    public interface addChooseListener {
        void getChooseQuestion(QuestionBean questionBean);
    }

    @Override
    public int getItemCount() {
        return questionBeenList == null ? 0 : questionBeenList.size();
    }

    static abstract class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_question_title)
        TextView tvTitle;
        @BindView(R.id.tv_question_number)
        TextView tvNumber;
        @BindView(R.id.iv_required)
        ImageView ivRequired;

        Context context;

        ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            context = itemView.getContext();
        }

    }

    static class RadioViewHolder extends QuestionAdapter.ViewHolder {

        @BindView(R.id.rg_choice)
        RadioGroup rgChoice;
        @BindView(R.id.progressBar)
        ProgressBar progressBar;

        RadioViewHolder(View itemView) {
            super(itemView);
        }

    }

    static class CheckBoxViewHolder extends QuestionAdapter.ViewHolder {

        @BindView(R.id.ll_checkbox)
        LinearLayout llCheckBox;
        @BindView(R.id.progressBar)
        ProgressBar progressBar;

        CheckBoxViewHolder(View itemView) {
            super(itemView);
        }

    }

    static class TextViewHolder extends QuestionAdapter.ViewHolder {

        @BindView(R.id.et_text)
        FlatEditText etText;

        TextViewHolder(View itemView) {
            super(itemView);
        }


    }

    static class PictureViewHolder extends QuestionAdapter.ViewHolder {

        @BindView(R.id.iv_picture)
        ImageView ivPicture;
        @BindView(R.id.iv_change)
        ImageView ivChange;
        @BindView(R.id.ngl_images)
        NineGridImageView imagesView;

        onItemImageListener onItemImageListener;

        private NineGridImageViewAdapter<String> mAdapter = new NineGridImageViewAdapter<String>() {


            List<ImageView> imageViewList=new ArrayList<>();

            @Override
            protected void onDisplayImage(Context context, ImageView imageView, String s) {
                Glide.with(context)
                        .load(s)
                        .into(imageView);
                imageViewList.add(imageView);
            }

            @Override
            protected ImageView generateImageView(Context context) {
                return super.generateImageView(context);
            }

            @Override
            protected void onItemImageClick(Context context, int index, List<String> list) {
//                super.onItemImageClick(context, index, list);
                onItemImageListener.onClick(index, list, imageViewList.get(index));
            }
        };


        PictureViewHolder(View itemView) {
            super(itemView);
            imagesView.setAdapter(mAdapter);
        }

        public void bind(QuestionBean questionBean) {
            imagesView.setImagesData(questionBean.getPictureList());
        }

        void setOnItemImageListener(PictureViewHolder.onItemImageListener onItemImageListener) {
            this.onItemImageListener = onItemImageListener;
        }

        interface onItemImageListener {

            void onClick(int index, List<String> list, ImageView imageView);
        }
    }

    static class LocationViewHolder extends QuestionAdapter.ViewHolder {

        @BindView(R.id.et_location)
        FlatEditText etLocation;
        @BindView(R.id.rv_location)
        RecyclerView rvLocation;
        @BindView(R.id.progressBar)
        ProgressBar progressBar;
        @BindView(R.id.iv_location)
        ImageView ivLocation;


        LocationViewHolder(View itemView) {
            super(itemView);
        }
    }

    static class TimeViewHolder extends QuestionAdapter.ViewHolder {

        @BindView(R.id.et_time)
        FlatEditText etTime;

        TimeViewHolder(View itemView) {
            super(itemView);
        }
    }
}
